// @flow
import { applyMiddleware, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import makeRootReducer from './reducers'
import { createMiddleware, createLoader } from 'redux-storage'
import createEngine from 'redux-storage-engine-localstorage'
import filter from 'redux-storage-decorator-filter'
// import { updateLocation } from './location'
import { SAVE_ID, SAVE_DEVICE_DATA } from 'store/modules/deviceCard'
import { USER_ID } from 'store/modules/user'
import { USER_MENU } from 'store/modules/menu'

export const storeHelper: {asyncReducers: Object; unsubscribeHistory?: Object} = {
  asyncReducers: {}
}

export default (initialState: Object = {}) => {
  // ======================================================
  // Middleware Configuration
  // ======================================================
  let engine = createEngine('k2alpha')
  engine = filter(engine, ['deviceCard', 'user', 'menu'])
  const middleware = [
    thunk,
    createMiddleware(engine, [], [SAVE_ID, SAVE_DEVICE_DATA, USER_ID, USER_MENU])
    // createMiddleware(engine, [], [USER_ID])
  ]

  // ======================================================
  // Store Enhancers
  // ======================================================
  const enhancers = []

  let composeEnhancers = compose

  if (__DEV__) {
    const composeWithDevToolsExtension = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    if (typeof composeWithDevToolsExtension === 'function') {
      composeEnhancers = composeWithDevToolsExtension
    }
  }

  // To unsubscribe, invoke `store.unsubscribeHistory()` anytime
  // storeHelper.unsubscribeHistory = browserHistory.listen(updateLocation(store))

  // ======================================================
  // Store Instantiation and HMR Setup
  // ======================================================
  const store = createStore(
    makeRootReducer(),
    initialState,
    composeEnhancers(
      applyMiddleware(...middleware),
      ...enhancers
    )
  )

  const load = createLoader(engine)
  load(store)
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      const reducers = require('./reducers').default
      store.replaceReducer(reducers(storeHelper.asyncReducers))
    })
  }

  return store
}
